<template>
  <div class="performance-monitor">
    <div class="monitor-header">
      <h3>性能监控</h3>
      <div class="header-actions">
        <Button @click="refreshMetrics" type="primary" size="small">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新
        </Button>
        <Button @click="clearCache" type="default" size="small">
          <IconifyIcon icon="ant-design:delete-outlined" />
          清除缓存
        </Button>
      </div>
    </div>

    <div class="monitor-content">
      <!-- 性能指标卡片 -->
      <Row :gutter="16" class="metrics-row">
        <Col :span="6">
          <Card class="metric-card">
            <Statistic
              title="API响应时间"
              :value="metrics.apiResponseTime"
              suffix="ms"
              :value-style="{
                color: getResponseTimeColor(metrics.apiResponseTime),
              }"
            />
          </Card>
        </Col>
        <Col :span="6">
          <Card class="metric-card">
            <Statistic
              title="缓存命中率"
              :value="metrics.cacheHitRate"
              suffix="%"
              :value-style="{
                color: getCacheHitRateColor(metrics.cacheHitRate),
              }"
            />
          </Card>
        </Col>
        <Col :span="6">
          <Card class="metric-card">
            <Statistic
              title="活跃连接数"
              :value="metrics.activeConnections"
              :value-style="{ color: '#1890ff' }"
            />
          </Card>
        </Col>
        <Col :span="6">
          <Card class="metric-card">
            <Statistic
              title="错误率"
              :value="metrics.errorRate"
              suffix="%"
              :value-style="{ color: getErrorRateColor(metrics.errorRate) }"
            />
          </Card>
        </Col>
      </Row>

      <!-- 缓存统计 -->
      <Card title="缓存统计" class="cache-stats-card">
        <Row :gutter="16">
          <Col :span="8">
            <div class="cache-stat">
              <div class="stat-label">缓存条目数</div>
              <div class="stat-value">{{ cacheStats.size }}</div>
            </div>
          </Col>
          <Col :span="8">
            <div class="cache-stat">
              <div class="stat-label">内存使用</div>
              <div class="stat-value">{{ formatBytes(cacheMemoryUsage) }}</div>
            </div>
          </Col>
          <Col :span="8">
            <div class="cache-stat">
              <div class="stat-label">缓存键</div>
              <div class="stat-value">{{ cacheStats.keys.length }}</div>
            </div>
          </Col>
        </Row>

        <div class="cache-keys">
          <h4>缓存键列表</h4>
          <div class="keys-list">
            <Tag
              v-for="key in cacheStats.keys.slice(0, 10)"
              :key="key"
              closable
              @close="removeCacheKey(key)"
            >
              {{ key }}
            </Tag>
            <span v-if="cacheStats.keys.length > 10" class="more-keys">
              +{{ cacheStats.keys.length - 10 }} 更多
            </span>
          </div>
        </div>
      </Card>

      <!-- 性能图表 -->
      <Row :gutter="16" class="charts-row">
        <Col :span="12">
          <Card title="API响应时间趋势" class="chart-card">
            <div ref="responseTimeChart" class="chart-container"></div>
          </Card>
        </Col>
        <Col :span="12">
          <Card title="缓存命中率趋势" class="chart-card">
            <div ref="cacheHitRateChart" class="chart-container"></div>
          </Card>
        </Col>
      </Row>

      <!-- 性能日志 -->
      <Card title="性能日志" class="logs-card">
        <div class="logs-header">
          <Select v-model="logLevel" style="width: 120px" size="small">
            <SelectOption value="all">全部</SelectOption>
            <SelectOption value="error">错误</SelectOption>
            <SelectOption value="warning">警告</SelectOption>
            <SelectOption value="info">信息</SelectOption>
          </Select>
          <Button @click="clearLogs" type="text" size="small">
            清空日志
          </Button>
        </div>

        <div class="logs-content">
          <div
            v-for="log in filteredLogs"
            :key="log.id"
            class="log-item"
            :class="`log-${log.level}`"
          >
            <div class="log-time">{{ formatTime(log.timestamp) }}</div>
            <div class="log-level">{{ log.level.toUpperCase() }}</div>
            <div class="log-message">{{ log.message }}</div>
            <div class="log-duration" v-if="log.duration">
              {{ log.duration }}ms
            </div>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import {
  Button,
  Card,
  Row,
  Col,
  Statistic,
  Tag,
  Select,
  SelectOption,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { rboApi } from '#/api/rbo-api';

// 性能指标接口
interface PerformanceMetrics {
  apiResponseTime: number;
  cacheHitRate: number;
  activeConnections: number;
  errorRate: number;
}

interface PerformanceLog {
  id: string;
  timestamp: number;
  level: 'info' | 'warning' | 'error';
  message: string;
  duration?: number;
}

// 响应式数据
const metrics = ref<PerformanceMetrics>({
  apiResponseTime: 0,
  cacheHitRate: 0,
  activeConnections: 0,
  errorRate: 0,
});

const cacheStats = ref({ size: 0, keys: [] as string[] });
const cacheMemoryUsage = ref(0);
const logs = ref<PerformanceLog[]>([]);
const logLevel = ref('all');

// 图表引用
const responseTimeChart = ref<HTMLElement>();
const cacheHitRateChart = ref<HTMLElement>();

// 计算属性
const filteredLogs = computed(() => {
  if (logLevel.value === 'all') {
    return logs.value;
  }
  return logs.value.filter((log) => log.level === logLevel.value);
});

// 方法
const refreshMetrics = async () => {
  try {
    // 模拟获取性能指标
    metrics.value = {
      apiResponseTime: Math.random() * 200 + 50,
      cacheHitRate: Math.random() * 30 + 70,
      activeConnections: Math.floor(Math.random() * 100) + 10,
      errorRate: Math.random() * 5,
    };

    // 获取缓存统计
    const stats = rboApi.getCacheStats();
    cacheStats.value = stats;
    cacheMemoryUsage.value = stats.size * 1024; // 估算内存使用

    addLog('info', '性能指标已刷新');
    message.success('性能指标已更新');
  } catch (error) {
    addLog('error', '刷新性能指标失败');
    message.error('刷新失败');
  }
};

const clearCache = () => {
  rboApi.clearCache();
  cacheStats.value = { size: 0, keys: [] };
  cacheMemoryUsage.value = 0;
  addLog('info', '缓存已清除');
  message.success('缓存已清除');
};

const removeCacheKey = (key: string) => {
  // 这里可以实现删除特定缓存键的逻辑
  addLog('info', `缓存键已删除: ${key}`);
};

const clearLogs = () => {
  logs.value = [];
};

const addLog = (
  level: 'info' | 'warning' | 'error',
  message: string,
  duration?: number,
) => {
  logs.value.unshift({
    id: `log_${Date.now()}`,
    timestamp: Date.now(),
    level,
    message,
    duration,
  });

  // 限制日志数量
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(0, 100);
  }
};

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString();
};

const formatBytes = (bytes: number) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const getResponseTimeColor = (time: number) => {
  if (time < 100) return '#52c41a';
  if (time < 200) return '#faad14';
  return '#f5222d';
};

const getCacheHitRateColor = (rate: number) => {
  if (rate > 90) return '#52c41a';
  if (rate > 70) return '#faad14';
  return '#f5222d';
};

const getErrorRateColor = (rate: number) => {
  if (rate < 1) return '#52c41a';
  if (rate < 5) return '#faad14';
  return '#f5222d';
};

// 性能监控定时器
let metricsTimer: NodeJS.Timeout | null = null;
letmetricsTimerletmetricsTimer;

// 生命周期
onMounted(() => {
  refreshMetrics();

  // 每30秒自动刷新指标
  metricsTimer = setInterval(() => {
    refreshMetrics();
  }, 30000);

  // 添加一些示例日志
  addLog('info', '性能监控已启动');
  addLog('info', '缓存系统运行正常');
});

onUnmounted(() => {
  if (metricsTimer) {
    clearInterval(metricsTimer);
  }
});
</script>

<style lang="less" scoped>
.performance-monitor {
  height: 100%;
  display: flex;
  flex-direction: column;

  .monitor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .monitor-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;

    .metrics-row {
      margin-bottom: 16px;

      .metric-card {
        text-align: center;
      }
    }

    .cache-stats-card {
      margin-bottom: 16px;

      .cache-stat {
        text-align: center;
        padding: 16px;

        .stat-label {
          color: #666;
          font-size: 14px;
          margin-bottom: 8px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #1890ff;
        }
      }

      .cache-keys {
        margin-top: 16px;

        h4 {
          margin-bottom: 12px;
        }

        .keys-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;

          .more-keys {
            color: #666;
            font-size: 12px;
            line-height: 22px;
          }
        }
      }
    }

    .charts-row {
      margin-bottom: 16px;

      .chart-card {
        .chart-container {
          height: 300px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #666;
          background: #fafafa;
          border-radius: 4px;
        }
      }
    }

    .logs-card {
      .logs-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
      }

      .logs-content {
        max-height: 400px;
        overflow-y: auto;

        .log-item {
          display: flex;
          align-items: center;
          padding: 8px 12px;
          border-bottom: 1px solid #f0f0f0;
          font-size: 12px;

          &:last-child {
            border-bottom: none;
          }

          &.log-error {
            background: #fff2f0;
            border-left: 3px solid #ff4d4f;
          }

          &.log-warning {
            background: #fffbe6;
            border-left: 3px solid #faad14;
          }

          &.log-info {
            background: #f6ffed;
            border-left: 3px solid #52c41a;
          }

          .log-time {
            width: 80px;
            color: #666;
          }

          .log-level {
            width: 60px;
            font-weight: bold;
          }

          .log-message {
            flex: 1;
            margin: 0 12px;
          }

          .log-duration {
            width: 60px;
            text-align: right;
            color: #666;
          }
        }
      }
    }
  }
}
</style>
